package api;

import dao.User;
import dao.UserDao;

import javax.crypto.spec.OAEPParameterSpec;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取到用户名和用户密码
        req.setCharacterEncoding("gb2312");
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        if(username==null || password==null || username.equals("") || password.equals(""))
        {
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("还没输入用户名或者密码");
            return;
        }
        //2.和数据库验证
         UserDao userDao=new UserDao();//创建连接
         User user= userDao.getUserByName(username);//在数据库中查找
        if(user==null)//用户不存在
        {
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("用户名不存在或者密码错误");
            return;
        }
        if(!password.equals(user.getPassword()))//密码错误
        {
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("密码错误");
            return;
        }

          //都ok,创建会话
            HttpSession session = req.getSession(true);//存在查询，不存在创建，生成键值对
            //将用户的信息保存到
            session.setAttribute("user", user);
            //跳转页面
            resp.sendRedirect("blog_list.html");

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //检测当前的登陆状态
        //1.创建会话
        HttpSession session= req.getSession();
        //当会话为空的时候
        if(session==null)
        {
            //返回403
            resp.setStatus(403);
            return;
        }
        //当会话存在，看看对象是否存在
        User user=(User) session.getAttribute("user");
        if(user==null)
        {
            //返回403
            resp.setStatus(403);
            return;
        }
        //返回两百表示已经登录了
        resp.setStatus(200);

    }
}
